const jwt = require("jsonwebtoken");
const { PRIVATE_KEY, PUBLIC_KEY } = require("../app/config");

// 验证登录以后 进一步的token  找到是谁的账号

const verifyToken = async (ctx, next) => {
  try {
    let token = ctx.request.header.authorization;
    token = token.replace("Bearer ", "");
    //   console.log(token);
    // 机密token
    const res = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    console.log("token 验证成功");
    ctx.user = res;
  } catch {
    console.log("token验证失败");
    return ctx.app.emit("error", new Error("token验证失败"), ctx);
  }
  await next();
};

module.exports = {
  verifyToken,
};
